﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfDevelopHelper.ViewModel;
using System.Reflection;
using FieldTemplate;
using System.Configuration;
using System.Xml.Linq;
using System.Data;

namespace WpfDevelopHelper
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            SingleMainWindow = this;

        }

        public static MainWindow SingleMainWindow;

        //private void GenerateColumnClick(object sender, RoutedEventArgs e)
        //{
        //    if (string.IsNullOrWhiteSpace(txtTemplate.SelectedText))
        //        return;
        //    int index = datagrid2.Columns.Count;
            
        //    index++;
        //    DataGridTextColumn column = new DataGridTextColumn()
        //    {
        //        Header = txtTemplate.SelectedText,
        //        Width = new DataGridLength(1, DataGridLengthUnitType.Star),
        //        Binding = new Binding() { Path = new PropertyPath($"cl{index.ToString()}") }
        //    };
        //    datagrid2.Columns.Add(column);
            
            

        //}

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //XElement x;
            //Assembly.Load()
            //System.Activator.CreateInstance()
            //var obj=  Assembly.LoadFrom("WpfDevelopHelper.exe").CreateInstance("WpfDevelopHelper.EnumFieldSetVm");
            //Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //if (ConfigurationManager.AppSettings.AllKeys.Contains("FieldTypes"))
            //{
            //    string value = config.AppSettings.Settings["FieldTypes"].Value;

            //    ConfigurationSection FieldTypes = config.GetSection("FieldTypes");
            //}
            //else
            //{
            //}

            //List<FieldInfo> fieldInfos = new List<FieldInfo>()
            //{
            //    new FieldInfo(){FieldName="ordernum",FieldDescrible="顺序数",Assembly="WpfDevelopHelper.exe",FullName="WpfDevelopHelper.OrderNumFieldSetVm"},
            //    new FieldInfo(){FieldName="randomnum",FieldDescrible="随机数",Assembly="WpfDevelopHelper.exe",FullName="WpfDevelopHelper.RandomNumFieldSetVm"},

            //};

            //XMLSerialize.serialize_to_xml(Directory.GetCurrentDirectory() + "/FieldTypes.xml",fieldInfos);


            //var tt= XMLSerialize.deserialize_from_xml(Directory.GetCurrentDirectory() + "/FieldTypes.xml", typeof(List<FieldInfo>));

        }

        private void AddBtn_Click(object sender, RoutedEventArgs e)
        {
            popup.IsOpen = true;
        }


    }

    //public class MainWindowViewModel : ViewModelSelfBase
    //{


    //    //public string Output
    //    //{
    //    //    get { return GetValue<string>("Output"); }
    //    //    set { SetValue("Output", value); }
    //    //}

    //    //public string TemplateText
    //    //{
    //    //    get { return GetValue<string>("TemplateText"); }
    //    //    set { SetValue("TemplateText", value); }
    //    //}



    //    public MainWindowViewModel()
    //    {
    //        GenerateClick = new RelayCommand(Generateclick);

    //        CReplaceItems = new ObservableCollection<CReplace>() {  };
    //        CReplaceList = new ObservableCollection<CRepList>() { };
    //    }
    //    public ICommand GenerateClick { get; set; }
    //    public void Generateclick()
    //    {
    //        if (string.IsNullOrWhiteSpace(TemplateText))
    //            return;
    //        Output = string.Empty;
    //        DataGrid dg = MainWindow.SingleMainWindow?.datagrid2;
    //        if (dg == null)
    //            return;

    //        foreach (var repitem in CReplaceList)
    //        {
    //            string tmp = TemplateText;
    //            int index = 1;


    //            foreach (var reCol in dg.Columns)
    //            {
    //                string property = string.Empty;
    //                switch (index++)
    //                {
    //                    case 1: property = repitem.cl1; break;
    //                    case 2: property = repitem.cl2; break;
    //                    case 3: property = repitem.cl3; break;
    //                    case 4: property = repitem.cl4; break;
    //                    case 5: property = repitem.cl5; break;
    //                    case 6: property = repitem.cl6; break;
    //                    case 7: property = repitem.cl7; break;
    //                    case 8: property = repitem.cl8; break;
    //                    case 9: property = repitem.cl9; break;

    //                    default:
    //                        break;
    //                }
    //                tmp=tmp.Replace(reCol.Header.ToString(), property);
    //            }
    //            Output += "\r\n" + tmp;
    //        }

    //        //Output = output;
    //    }

    //    public ObservableCollection<CReplace> CReplaceItems
    //    {
    //        get { return GetValue<ObservableCollection<CReplace>>("CReplaceItems"); }
    //        set { SetValue("CReplaceItems", value); }
    //    }
    //    public ObservableCollection<CRepList> CReplaceList
    //    {
    //        get { return GetValue<ObservableCollection<CRepList>>("CReplaceList"); }
    //        set { SetValue("CReplaceList", value); }
    //    }

    //}

    public class CReplace
    {
        public string srcstr { get; set; }
        public string RepColName { get; set; }

    }

    public class CRepList
    {
        public string cl1 { get; set; }
        public string cl2 { get; set; }
        public string cl3 { get; set; }
        public string cl4 { get; set; }
        public string cl5 { get; set; }
        public string cl6 { get; set; }
        public string cl7 { get; set; }
        public string cl8 { get; set; }
        public string cl9 { get; set; }

    }



    public class DataGenerateViewModel : ViewModelBase
    {



        private ObservableCollection<FieldSetVmBase> _ListField;
        public ObservableCollection<FieldSetVmBase> ListField
        {
            get
            {
                return _ListField;
            }
            set
            {
                _ListField = value;
                RaisePropertyChanged("ListField");
            }
        }
        private FieldSetVmBase _SelectedField;
        public FieldSetVmBase SelectedField
        {
            get
            {
                return _SelectedField;
            }
            set
            {
                _SelectedField = value;

                if(_SelectedField!=null)
                {
                    Content = _SelectedField.SetPanel;
                }


                RaisePropertyChanged("SelectedField");
            }
        }

        private UserControl _Content;
        public UserControl Content
        {
            get
            {
                return _Content;
            }
            set
            {
                _Content = value;
                RaisePropertyChanged("Content");
            }
        }

        private List<FieldInfo> _FieldTypes;
        public List<FieldInfo> FieldTypes
        {
            get
            {
                return _FieldTypes;
            }
            set
            {
                _FieldTypes = value;
                RaisePropertyChanged("FieldTypes");
            }
        }

        public FieldInfo SelectedFieldType { get; set; }

        public DataGenerateViewModel()
        {
            SelectTmplateCmd = new RelayCommand(SelectTmplateClick);
            SaveTmplateCmd =new RelayCommand(SaveTmplateClick);
            AddFieldCmd = new RelayCommand(AddFieldClick);
            DeleteFieldCmd = new RelayCommand(DeleteFieldClick);
            DeleteAllFieldCmd=new RelayCommand(DeleteAllFieldClick);
            GenerateDataCmd = new RelayCommand(GenerateDataClick);
            DeleteTemplateCmd = new RelayCommand(DeleteTemplateClick);
            

            DataCount = 10;
            ListField = new ObservableCollection<FieldSetVmBase>();


            FieldTypes = XMLSerialize.deserialize_from_xml(Directory.GetCurrentDirectory() + "/FieldTypes.xml", typeof(List<FieldInfo>)) as List<FieldInfo>;


            lstTemplates = DeserializFromFile();
        }

        private DataTable GenerateTabele()
        {
            DataTable dt = new DataTable();
            foreach(var field in ListField)
            {
                dt.Columns.Add(field.FieldName, typeof(string));
            }
            //outputtable= dt.DefaultView;
            return dt;
        }

        private DataView _outputtable;
        public DataView outputtable
        {
            get
            {
                return _outputtable;
            }
            set
            {
                _outputtable = value;
                RaisePropertyChanged("outputtable");
            }
        }




        public ICommand AddFieldCmd { get; set; }
        public ICommand DeleteFieldCmd { get; set; }
        public ICommand DeleteAllFieldCmd { get; set; }
        public ICommand GenerateDataCmd { get; set; }
        public ICommand SaveTmplateCmd { get; set; }
        public ICommand SelectTmplateCmd { get; set; }

        public ICommand DeleteTemplateCmd { get; set; }

        

        public string TemplateName { get; set; }//学生信息

        public void SaveTmplateClick()
        {
            SaveAttention saveAttention = new SaveAttention();
            saveAttention.Owner = MainWindow.SingleMainWindow;
            if (saveAttention.ShowDialog()!=true)
            {
                return;
            }
            TemplateName = saveAttention.SaveName;


            TemplateModel templateModel = new TemplateModel()
            {
                TemplateName = TemplateName,
                OutputTemplate = OutputTemplate,
                fieldinfos = new List<Fieldinfo>()
            };
            foreach(var item in ListField)
            {
                templateModel.fieldinfos.Add(item.Serialize());
            }

            if (lstTemplates.ToList(). Exists(a => { return a.TemplateName == templateModel.TemplateName; }))
            {
                var ret=MessageBox.Show("已有同名模板，该操作将覆盖原有模板，是否继续?","提醒", MessageBoxButton.YesNo,  MessageBoxImage.Question);
                if(ret != MessageBoxResult.Yes)
                    return;

                lstTemplates.Remove(lstTemplates.FirstOrDefault(a => { return a.TemplateName == templateModel.TemplateName; }));


            }
            lstTemplates.Add(templateModel);

            


            Serialize2File(lstTemplates);



        }
        public void SelectTmplateClick()
        {
            if(SelectedTmplate!=null)
            {
                OutputTemplate = SelectedTmplate.OutputTemplate;
                ListField = SelectedTmplate.GenerateFieldSetVm( FieldTypes);
                SelectedField = ListField.FirstOrDefault();
            }

        }
        public void DeleteTemplateClick()
        {
            if (SelectedTmplate != null)
            {
                lstTemplates.Remove(SelectedTmplate);
                Serialize2File(lstTemplates);
            }

        }
        


        private ObservableCollection<TemplateModel> _lstTemplates;
        public ObservableCollection<TemplateModel> lstTemplates
        {
            get
            {
                return _lstTemplates;
            }
            set
            {
                _lstTemplates = value;
                RaisePropertyChanged("lstTemplates");
            }
        }
        private TemplateModel _SelectedTmplate;
        public TemplateModel SelectedTmplate
        {
            get
            {
                return _SelectedTmplate;
            }
            set
            {
                _SelectedTmplate = value;
                RaisePropertyChanged("SelectedTmplate");
            }
        }

        public void AddFieldClick()
        {
            FieldSetVmBase vm=null;
            if(SelectedFieldType==null)
            {
                MessageBox.Show("请先选择列类型");
                return;
            }


            vm = SelectedFieldType.ReflactionCreateInstance() as FieldSetVmBase;


            ListField.Add(vm);
            SelectedField = vm;
        }



        public void DeleteFieldClick()
        {
            if(SelectedField==null)
            {
                MessageBox.Show("请先选择列表中的一条数据");
                return;
            }

            ListField.Remove(SelectedField);
            SelectedField = ListField.LastOrDefault();

        }
        public void DeleteAllFieldClick()
        {

            ListField.Clear();
        }

        private int _DataCount;
        public int DataCount
        {
            get
            {
                return _DataCount;
            }
            set
            {
                _DataCount = value;
                RaisePropertyChanged("DataCount");
            }
        }

        private string _output;
        public string output
        {
            get
            {
                return _output;
            }
            set
            {
                _output = value;
                RaisePropertyChanged("output");
            }
        }


        private string _OutputTemplate;
        public string OutputTemplate
        {
            get
            {
                return _OutputTemplate;
            }
            set
            {
                _OutputTemplate = value;
                RaisePropertyChanged("OutputTemplate");
            }
        }



        public void GenerateDataClick()
        {
            if (ListField.Count == 0)
            {
                MessageBox.Show("请至少设置一列需要生成的内容");
                return;
            }

            
            if(string.IsNullOrWhiteSpace(OutputTemplate))
            {
                DataTable dt= GenerateTabele();
                string tmp = string.Empty;
                for (int i = 0; i < DataCount; i++)
                {
                    DataRow row = dt.NewRow();

                    foreach (var field in ListField)
                    {
                        string value= field.GetFieldValue();
                        tmp += " " + value;
                        row[field.FieldName] = value;
                    }
                    dt.Rows.Add(row);
                    tmp += "\r\n";
                    
                }

                outputtable = dt.DefaultView;
                output = tmp;
            }
            else
            {
                string outputTmp = string.Empty;
                for (int i = 0; i < DataCount; i++)
                {
                    string tmp = OutputTemplate;
                    foreach (var field in ListField)
                    {
                        string tmplate = "#" + field.FieldName + "#";

                       tmp= tmp.Replace(tmplate, field.GetFieldValue());

                    }
                    tmp += "\r\n";
                    outputTmp += tmp;
                }
                output += outputTmp;
            }


            
        }


        string filePath= Directory.GetCurrentDirectory() + "/binaryFile.bin";

        ObservableCollection<TemplateModel> DeserializFromFile()       // 二进制反序列化
        {
            ObservableCollection<TemplateModel> ret = new ObservableCollection<TemplateModel>();
            if (!File.Exists(filePath))
            {
                return ret;
            }

            FileStream fs = new FileStream(filePath, FileMode.Open);


            BinaryFormatter formatter = new BinaryFormatter();
            var tmp= formatter.Deserialize(fs);//序列化对象，写入ms流中  
            fs.Close();
            if (tmp is ObservableCollection<TemplateModel>)
                ret = tmp as ObservableCollection<TemplateModel>;
            return ret;
        }

        void Serialize2File(object obj)   // 二进制序列化
        {
            FileStream fs = new FileStream(filePath, FileMode.Create);

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, obj);//序列化对象，写入ms流中  

            fs.Close();
        }



    }

}
